﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

using System.Drawing.Printing;

namespace EnrollmentSystem
{
    public partial class frmOTRManager : Form
    {

        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();
        UnityScript[] eudat = new UnityScript[0]; 
        
        DataTable items = new DataTable();
        DataTable itemsDetail = new DataTable();

        DataTable students = new DataTable();
        DataTable data = new DataTable();

        bool stdErr = false;
        string bPlace = "";
        string birthDate = "";
        string address = "";

        public frmOTRManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }

        private void InitializeForm()
        {

            InitializeItemTable();
            btnPrint.Click +=new EventHandler(btnPrint_Click);
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            btnGenerate.Click += new EventHandler(btnGenerate_Click);
            txtName.TextChanged += new EventHandler(txtName_TextChanged);
            LoadData();
        }

        void btnGenerate_Click(object sender, EventArgs e)
        {
            if (txtStudentNumber.Text != "")
            {
                LoadSearchData();
            }
        }

        void txtName_TextChanged(object sender, EventArgs e)
        {
            DataRow[] dr = students.Select("fName='" + txtName.Text + "'");
            if (dr.Length == 1)
            {
                txtStudentNumber.Text = dr[0]["fNumber"].ToString();
                txtCourse.Text = dr[0]["fCourse"].ToString();
                txtDept.Text = dr[0]["fDepartment"].ToString();
                txtSecondary.Text = dr[0]["fSecondarySchool"].ToString();
                txtYearGraduated.Text = dr[0]["fYearGraduated"].ToString();
                bPlace = dr[0]["fPlaceOfBirth"].ToString();
                birthDate = dr[0]["fBirthDate"].ToString();
                address = dr[0]["fAddress"].ToString();

                txtStudentNumber.ForeColor = Color.Black;
                txtName.ForeColor = Color.Black;
                txtCourse.ForeColor = Color.Black;
                txtDept.ForeColor = Color.Black;
                txtSecondary.ForeColor = Color.Black;
                txtYearGraduated.ForeColor = Color.Black;

                lblWarningEntry.Text = "";
                stdErr = false;
            }
            else //if (txtSupplierName.Text.Length > 0)
            {
                if (!stdErr)
                {
                    txtStudentNumber.Text = "N/A";
                    txtCourse.Text = "N/A";
                    txtDept.Text = "N/A";
                    txtSecondary.Text = "N/A";
                    txtYearGraduated.Text = "N/A";
                    bPlace = "";
                    birthDate = "";
                    address = "";

                    txtName.ForeColor = Color.Red;
                    txtStudentNumber.ForeColor = Color.Red;
                    txtCourse.ForeColor = Color.Red;
                    txtDept.ForeColor = Color.Red;
                    txtSecondary.ForeColor = Color.Red;
                    txtYearGraduated.ForeColor = Color.Red;

                    lblWarningEntry.Text = "Warning: Student not found in the database.";
                    stdErr = true;
                }
            }
        }

        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc);
                pnlMsg.Visible = false;
            });
        }

        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "LOADSEARCH":
                        UnityScript[] edat;
                        proc.DBPUX_Data_Fetch(out edat);

                        data = edat[0].ToDataTable();
                        items.Rows.Clear();
                        ConstructItems();

                        grdItems.DataSource = items;

                        break;
                    case "LOAD":
                        proc.DBPUX_Data_Fetch(out dat);
                        students = dat[0].ToDataTable();

                        txtStudentNumber.AutoCompleteCustomSource.AddRange(dat[0].ToList<string>(0));
                        txtName.AutoCompleteCustomSource.AddRange(dat[0].ToList<string>(1));

                        break;
                }
            });
        }

        void FormatGrid()
        {
            grdItems.Columns[0].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[2].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[3].Width = (grdItems.Width * 20) / 100;
            grdItems.Columns[4].Width = (grdItems.Width * 20) / 100;
           

            grdItems.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdItems.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
           
            lblStatus.Text = grdItems.Rows.Count + " Records";
            grdItems.Sort(grdItems.Columns[0], ListSortDirection.Ascending);
            
        }

        void InitializeItemTable()
        {
            items.Columns.Add("TERM");
            items.Columns.Add("NAME OF COURSE");
            items.Columns.Add("DESCRIPTIVE TITLE");
            items.Columns.Add("GRADES FINAL");
            items.Columns.Add("CREDIT EARNED");

         

            

            grdItems.DataSource = items;

            grdItems.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grdItems.Columns[2].DefaultCellStyle.Format = "#,#0.00";
            grdItems.Columns[3].DefaultCellStyle.Format = "#,#0.00";
            grdItems.Columns[4].DefaultCellStyle.Format = "#,#0.00";

        }
        void LoadData()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            proc.ProcStart();
            UnityScript x = new UnityScript("LOAD", 4);
            x.Script_Add(Script.DBPUX_BEGIN);
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblStudentProfile"));
            x.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(x);
        }
        void LoadSearchData()
        {

            UnityScript U = new UnityScript("LOADSEARCH", 4);
            U.Script_Add(Script.DBPUX_BEGIN);
            //U.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblstudentprofile"));

            U.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, t1.fEnrollmentNumber, t1.fStudentNumber, fSchoolYear, ffSubjectCode, ffSubjectName, ffGrade, ffUnit, fStamp FROM tblEnrollment t1 , " +
                    " (SELECT fEnrollmentNum, fSubjectCode AS ffSubjectCode, fGrade AS ffGrade, fUnits AS ffUnit FROM tblgrades t22 ) AS t2 , " +
                    " (SELECT fID AS ffID, fCode AS ffSubjectName FROM tblsubjectplanner t33 ) AS t3  " +
                    "WHERE (t1.fEnrollmentNumber = t2.fEnrollmentNum) AND (ffSubjectCode = ffID) AND (t1.fStudentNumber = '{0}')",txtStudentNumber.Text ));
            
            

            U.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(U);
        }
        void ConstructItems()
        {

            for (int i = 0; i < data.Rows.Count; i++)
            {
                DataRow dr = items.NewRow();
                dr[0] = data.Rows[i][2].ToString();
                dr[1] = data.Rows[i][3].ToString();
                dr[2] = data.Rows[i][4].ToString();
                dr[3] = data.Rows[i][5].ToString();

                string grade = data.Rows[i][5].ToString();
                if(grade.Equals("DRP")) grade = "0";
                if(grade.Equals("NFE")) grade = "0";
                if(grade.Equals("UD")) grade = "0";
                if(grade.Equals("INC")) grade = "0";

                float fGrade = float.Parse(grade);
                if (fGrade >= 75)
                    dr[4] = data.Rows[i][6].ToString();
                else
                    dr[4] = "0";

                items.Rows.Add(dr);
            }


        }
        //printing
   
        int cnt = 0;
        int pp = 1;
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                pp = 1;
                //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left - 50;
            float rm = e.PageBounds.Width - 50;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 110;
            cFont = new Font("Arial", 10f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("Transcript of Records", new Font("Arial", 17f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));

            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Name: "+txtName.Text, cFont, Brushes.Black, lm, y, sf);
            e.Graphics.DrawString("Date: " + DateTime.Now.ToShortDateString(), cFont, Brushes.Black, lm+370, y, sf);
            y += ht;
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Address: "+address, cFont, Brushes.Black, lm, y, sf);
            e.Graphics.DrawString("Date of Admission: " + grdItems.Rows[0].Cells[0].Value.ToString(), cFont, Brushes.Black, lm + 370, y, sf);
            y += ht;
            e.Graphics.DrawString("Date of Birth: "+birthDate, cFont, Brushes.Black, lm, y, sf);
            e.Graphics.DrawString("College of : " + txtDept.Text, cFont, Brushes.Black, lm + 370, y, sf);
            y += ht;
            e.Graphics.DrawString("Place of Birth: "+bPlace, cFont, Brushes.Black, lm, y, sf);
            e.Graphics.DrawString("Degree/Course: " + txtCourse.Text, cFont, Brushes.Black, lm + 370, y, sf);
            y += ht;
            e.Graphics.DrawString("Secondary School: "+txtSecondary.Text, cFont, Brushes.Black, lm, y, sf);
            e.Graphics.DrawString("Date of Graduation:  " + txtDate.Text, cFont, Brushes.Black, lm + 370, y, sf);
            y += ht;
            e.Graphics.DrawString("Date of Graduation: " +txtYearGraduated.Text, cFont, Brushes.Black, lm, y, sf);
            //Column Header
            y += ht;
            y += ht;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));

            e.Graphics.DrawString("TERM", cFont, Brushes.Black, lm + 4, y, sf);
            e.Graphics.DrawString("COURSE", cFont, Brushes.Black, lm + 200, y, sf);
            e.Graphics.DrawString("DESCRIPTIVE TITLE", cFont, Brushes.Black, lm + 300, y, sf);
            e.Graphics.DrawString("GRADE" , cFont, Brushes.Black, lm + 580, y, sf);
            e.Graphics.DrawString("CREDIT EARNED" , cFont, Brushes.Black, lm + 650, y, sf);
            //Data
            y += ht * (1.5f);
            cFont = new Font("Arial", 9f, FontStyle.Regular);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            string name = "";
            int x = 1;
            while (cl <= lpp && cnt < grdItems.Rows.Count)
            {

                string str = grdItems.Rows[cnt].Cells[0].Value.ToString();
                if (!name.Equals(str))
                {
                    
                    e.Graphics.DrawString(str, cFont, Brushes.Black, lm + 4, y, sf);
                    name = grdItems.Rows[cnt].Cells[0].Value.ToString();
                }

                str = grdItems.Rows[cnt].Cells[1].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 200, y, sf);

                str = grdItems.Rows[cnt].Cells[2].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 300, y, sf);

                str = grdItems.Rows[cnt].Cells[3].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 600, y, sf);

                str = grdItems.Rows[cnt].Cells[4].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 700, y, sf);
                //str = grdItems.Rows[cnt].Cells[5].Value.ToString();
               // e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 720, y, sf);
                
                y += ht * (1.25f);
                cnt++;
                cl++;
            }
            //e.Graphics.DrawString("Total", cFont, Brushes.Blue, stx - 150, y + 10, sf);
            //e.Graphics.DrawString(, cFont, Brushes.Blue, stx - 4, y + 10, sf);

            if (cnt < grdItems.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                
                e.Graphics.DrawString("******************** Nothing Follows ********************", cFont, Brushes.Black, lm + 150, y + ht, new StringFormat());

                pp = 1;
                e.HasMorePages = false;
                cnt = 0;
            }
        }
     
        
    }
}
